package vip.learning.gateway.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import sun.awt.ConstrainableGraphics;

/**
 * @ClassName RecordTimeGatewayFilterFactory
 * @Description
 * @Author hubin
 * @Date 2022/1/11 20:20
 * @Version V1.0
 **/
@Component
@Slf4j
public class RecordTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {


    // 设置一个记录时间的key
    private static final String RECORD_TIME="record_time";

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain gatewayFilterChain) {

                String name = config.getName();
                String value = config.getValue();
                log.info("name:{},value:{}",name,value);

                if(value.equals("false")){
                    return null;
                }

                // 记录一下当前时间
                serverWebExchange.getAttributes().put(RECORD_TIME,System.currentTimeMillis());

                return gatewayFilterChain.filter(serverWebExchange).then(Mono.fromRunnable(new Runnable() {
                    @Override
                    public void run() {
                        // 获取请求之前时间
                        Long startTime
                                = serverWebExchange.getAttribute(RECORD_TIME);
                        // ms
                        Long time =  System.currentTimeMillis() - startTime;

                        log.info("当前这个请求所花费的时间 time = {} ms",time);

                    }
                }));
            }
        };
    }
}

